﻿using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO; 
using MyLib;
 
namespace PerformanceReport.AjaxPage
{
    /// <summary>
    /// GenerateReports 的摘要说明
    /// </summary>
    public class GenerateStepsReports : IHttpHandler 
    {
        string strSql;
        string strJson;
        string strPara;
        string strStartDate;
        string strEndDate;
        string strHtmlCount = string.Empty;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            strPara = context.Request["Para"];             //流程名
            strStartDate=context.Request["StartDate"];     //开始时间
            strEndDate = context.Request["EndDate"];       //结束时间

            strSql = "select Distinct Steplabel,ProcessName from Tasks";             
            string where = " where 1=1 ";
              where += " and ProcessName= '" + strPara.Trim() + "'";
            if (!string.IsNullOrEmpty(strStartDate))
            {
                where += " and  starttime >= to_date('" + strStartDate.Trim() + "','yyyy-MM-dd')";
            }
            if (!string.IsNullOrEmpty(strEndDate))
            {
                where += " and  starttime <= to_date('" + strEndDate.Trim() + "','yyyy-MM-dd')";
            }
            string StrSqlTotal = strSql + where;
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSqlTotal.ToString());

            //如果存在返回值的情况
            if (dt.Rows.Count > 0)
            {
                DataTable dtTemp = new DataTable();
                dtTemp.Columns.Add("Steplabel");
                dtTemp.Columns.Add("ProcessName");
                DataRow NewRow = dtTemp.NewRow();
                NewRow["Steplabel"] = dt.Rows[0]["Steplabel"].ToString();
                NewRow["ProcessName"] = dt.Rows[0]["ProcessName"].ToString();
                dtTemp.Rows.Add(NewRow);

                string strProcessStep = InitLine(dt);
                string strAvgTime = TotalAvgTime(dt, strPara, strStartDate, strEndDate);
                string strPrice = TotalAvgPrice();

                strJson = "[";

                //循环所有的行
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                strJson += "{'ProcessStep':'" + CheckText(strProcessStep.Trim()) + "',"
                         + "'AvgTime':'" + CheckText(strAvgTime.Trim()) + "',"
                         + "'Prices':'" + CheckText(strPrice.Trim()) + "'},";
                //}
                strJson = strJson.Substring(0, strJson.LastIndexOf(','));
                strJson += "]";
            }

             context.Response.Buffer = true;
             context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
             context.Response.Expires = 0;
             context.Response.CacheControl = "no-cache";
             context.Response.Write(strJson);
        }

        //流程审批步骤
        public string InitLine(DataTable dt)
        {
            string strHtml = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strHtml += dt.Rows[i]["Steplabel"].ToString().Trim() + ",";
            }
            return strHtml;
            //string strValue = strSubstrng(strHtml);
            //return strValue;
        }

        //public string strSubstrng(string str)
        //{ 
        //    string [] strs=str.Split(',');
        //    string s = "";
        //    for(int i=0;i<strs.Length;i++)
        //    {
        //         if(s=="")
        //         {
        //             s+="'"+strs[i]+"'";
        //         }
        //         else 
        //         {
        //            s+=",'"+strs[i]+"'";
        //         }
        //    }
        //    return s;
        //}

        //平均耗时曲线图
        public string TotalAvgTime(DataTable dt, string strProcessName, string strStartTime, string strEndTime)
        {
            //string strHtmlCount = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //string strSql = "select Count(Steplabel) as Steplabel,ProcessName,Status from Tasks where ProcessName= '" + strProcessName.Trim() + "' and Steplabel='" + dt.Rows[i]["Steplabel"].ToString() + "' and Status=3  group by Steplabel,ProcessName,Status";
                string strSql = "select  count(incident) cou,Steplabel,ProcessName, "
                    //+ "ROUND(TO_NUMBER(to_date(endtime,'yyyy-MM-dd hh24:mi:ss') - to_date(starttime,'yyyy-MM-dd hh24:mi:ss')) * 24) as times"
                             + "Round(SUM((endtime - starttime) * 24),2) as times"
                              + " from Tasks";
                            string where = " where 1=1 ";

                           where   += " and ProcessName= '" + strProcessName.Trim() + "'";
                           where += " and Steplabel='" + dt.Rows[i]["Steplabel"].ToString() + "'";
                           where += "  and status=3 ";
                if (!string.IsNullOrEmpty(strStartTime))
                {
                    where += " and  starttime >= to_date('" + strStartTime.Trim() + "','yyyy-MM-dd')";
                }
                if (!string.IsNullOrEmpty(strEndTime))
                {
                    where += " and  starttime <= to_date('" + strEndTime.Trim() + "','yyyy-MM-dd')";
                }
                where += " group by Steplabel,ProcessName";
                string StrSqlTotal = strSql + where;
                DataTable dtCount = DataAccess.Instance("BizDB").ExecuteDataTable(StrSqlTotal.ToString());
                if (dtCount.Rows.Count > 0)
                {
                    //四舍五入,保留一位有效数字
                    //int Min = int.Parse(dtCount.Rows[0]["times"].ToString());   //分钟
                    //int Result = Min / 60;    //小时
                    double time = double.Parse(dtCount.Rows[0]["times"].ToString());
                    string strValue = CountIndenct(strProcessName);
                    double Line = double.Parse(strValue);
                    //double Line = double.Parse(dtCount.Rows[0]["cou"].ToString());
                    //double Line = double.Parse(dtCount.Rows.Count.ToString());
                    double strAvgTime = Math.Round((time / Line), 1, MidpointRounding.AwayFromZero);    
                    //int strAvgTime = int.Parse(dtCount.Rows[0]["times"].ToString()) / dtCount.Rows.Count;
                    strHtmlCount += strAvgTime + ",";
                }
                else
                {
                    strHtmlCount += "0" + ",";
                }
            }

            //拼接series值
            string strHeader = "{ type: 'spline',color: '#89A54E',name:'平均耗时(曲线图)'" + "," + "data:" + "[";  
            string strEnd = "]}";
            //string strStyle = ",marker: {lineWidth: 2, lineColor: Highcharts.getOptions().colors[3],fillColor: 'white'}}";
            string strTotal = strHeader + strHtmlCount.TrimEnd(',') + strEnd;         
            return strTotal;
            //return strHtmlCount.TrimEnd(',');
        }

        //平均耗时柱状图
        public string TotalAvgPrice()
        { 
           string strVale= string.Empty;
           strVale = strHtmlCount.TrimEnd(',');
           string strHeader = "{ type: 'column',name:'平均耗时(柱状图)'" + "," + "data:" + "[";
           string strEnd = "]}";
           string strTotal = strHeader + strHtmlCount.TrimEnd(',') + strEnd;
           return strTotal;
        }

        //获取当前流程名的总实例数
        private string CountIndenct(string drpProcessName)
        {
            string strSq = "  select count(incident) as counts from incidents where  ProcessName= '" + drpProcessName.Trim() + "' and status=2";
            DataTable dtsq = DataAccess.Instance("BizDB").ExecuteDataTable(strSq.ToString());
            string strReturn = "";
            if (int.Parse(dtsq.Rows[0]["counts"].ToString()) > 0)
            {
                strReturn = dtsq.Rows[0]["counts"].ToString();
            }
            else
            {
                strReturn = "1";
            }
            return strReturn;
        }

        public string CheckText(string Str)
        {
            string ReturnString = "";
            ReturnString = Str.Replace(",", "#dou#");
            ReturnString = Str.Replace("'", "#dan#");
            return ReturnString;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
         
    }
}